import { Injectable } from '@angular/core';

import { QuoteBasic } from 'service/QuoteBasic';
import { IMAService } from 'interface/IMAService';

@Injectable()
export class MAService implements IMAService {

  connection;

  constructor() {

  }

  compute(quote:QuoteBasic, day:number = 5):Array<any>{
    const maList = [];
    const count = quote.close.length;

    if(day > 0) {
      for(let i=0; i<count; i++) {
        if(i < day) {
          let sum = 0;
          for(let j=0; j<=i; j++) {
            sum+=quote.close[j];
          }
          maList.push(parseFloat((sum/(i+1)).toFixed(4)));
          continue;
        }
        let sum = 0;
        for(let j=0; j<day; j++) {
          sum+=quote.close[i-j];
        }
        maList.push(parseFloat((sum/day).toFixed(4)));
      }
    }

    return maList;
  }

  update(quote:QuoteBasic, day:number, oldList:Array<any>) :Array<any> {

    const originCount = quote.close.length;
    const oldCount = oldList.length;
    const times = quote.time;

    if(originCount > 0 && day > 0) {

      if(oldCount === 0) {
        return this.compute(quote,day);
      }

      const start = (originCount - day) < 0 ? 0 : (originCount - day);
      const end = (originCount - 1) < 0 ? 0 : (originCount - 1);

      if (start > end) {
        return oldList;
      }

      let sum = 0;
      for(let i = start; i <= end; i++) {
        sum+=quote.close[i];
      }

      if (oldCount < originCount) {
        oldList.push(parseFloat((sum/(end-start+1)).toFixed(4)));
      } else {
        oldList[oldList.length -1] = parseFloat((sum/(end-start+1)).toFixed(4));
      }
    }

    return oldList;
  }
}
